package com.lixiaohan.lushudao.service.imlp;

import com.lixiaohan.lushudao.dao.RoamUserInfoMapper;
import com.lixiaohan.lushudao.pojo.RoamUserInfo;
import com.lixiaohan.lushudao.service.RoamUserInfoService;
import com.lixiaohan.lushudao.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

@Service
public class RoamUserInfoServiceImpl implements RoamUserInfoService {
    @Override
    public RoamUserInfo LoginUser(String userAcc) {
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            RoamUserInfoMapper mapper = sqlSession.getMapper(RoamUserInfoMapper.class);
            return mapper.LoginUser(userAcc);
        } catch (Exception e) {
            return null;
        } finally {
            if (sqlSession!=null)
                sqlSession.close();
        }
    }

    @Override
    public RoamUserInfo UpdateUserOther(RoamUserInfo userInfoSession,RoamUserInfo userInfo) {
        SqlSession sqlSession=null;
        try {
            Integer uidSession = userInfoSession.getUserId();//session中的uid
            sqlSession = MybatisUtils.getSqlSession();
            RoamUserInfoMapper mapper = sqlSession.getMapper(RoamUserInfoMapper.class);

            //不能改的东西不变
            userInfo.setUserId(uidSession);
            userInfo.setUserAcc(userInfoSession.getUserAcc());
            userInfo.setUserPwd(userInfoSession.getUserPwd());
            userInfo.setUserAccSelect(userInfoSession.getUserAccSelect());
            userInfo.setUserFirstTime(userInfoSession.getUserFirstTime());
            mapper.UpdateOneUser(userInfo);
            return userInfo;
        } catch (Exception e) {
            return null;
        } finally {
            if (sqlSession!=null)
                sqlSession.close();
        }
    }

    @Override
    public Integer LogoutUser(String email) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        RoamUserInfoMapper mapper = sqlSession.getMapper(RoamUserInfoMapper.class);
        Integer uid = mapper.FindUidByUserAcc(email);
        if (uid!=null) return mapper.LogoutByUid(uid);
        return 0;
    }

    @Override
    public Integer UpdateUserPassword(String userAcc, String password) {
        try {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            RoamUserInfoMapper mapper = sqlSession.getMapper(RoamUserInfoMapper.class);
            Integer success = mapper.updatePassword(userAcc,password);
            if (success<1){
                throw new IllegalArgumentException("修改失败");
            }
            return success;
        }catch (Exception e){
            throw new IllegalArgumentException("服务器出错");
        }
    }

}
